package com.gaojinqi.sys.modular.rbac.dao;

import com.gaojinqi.base.core.jpa.BaseRepository;
import com.gaojinqi.sys.modular.rbac.model.Role;
import com.gaojinqi.sys.modular.rbac.model.UserRoleMapping;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

/**
 * 用户-角色 - 数据访问层接口
 *
 * @author gaojinqi
 * @version 1.0
 * @since 2020年04月21日
 */
@Repository
public interface UserRoleRepository extends BaseRepository<UserRoleMapping, String> {

    @Query("select urm.role.roleId from UserRoleMapping urm where urm.user.userId = :userId order by urm.role.sort asc")
    List<String> findRoleIdsByUserId(@Param("userId") String userId);

    @Query("select urm.role from UserRoleMapping urm where urm.user.userId = :userId order by urm.role.sort asc")
    Page<Role> pageByUserId(@Param("userId") String userId, Pageable pageable);

    @Query("select urm.role from UserRoleMapping urm where urm.user.userId = :userId order by urm.role.sort asc")
    List<Role> findRolesByUserId(@Param("userId") String userId);

    @Query("select urm.role from UserRoleMapping urm where urm.user.userName = :userName order by urm.role.sort asc")
    List<Role> findRolesByUserName(@Param("userName") String userName);

    @Modifying
    @Query("delete from UserRoleMapping urm where urm.role.roleId = :roleId")
    void deleteByRoleId(@Param("roleId") String roleId);

    @Modifying
    @Query("delete from UserRoleMapping urm where urm.role.roleId in (:roleIds)")
    void deleteByRoleIds(@Param("roleIds") Collection<String> roleIds);

    @Modifying
    @Query("delete from UserRoleMapping urm where urm.user.userId = :userId")
    void deleteByUserId(@Param("userId") String userId);

    @Modifying
    @Query("delete from UserRoleMapping urm where urm.user.userId in (:userIds)")
    void deleteByUserIds(@Param("userIds") Collection<String> userIds);

}
